package config

import (
	"fmt"
	"github.com/joho/godotenv"
	"log"
	"os"
)

type Config struct {
	DBHost             string
	DBPort             string
	DBUser             string
	DBPassword         string
	DBName             string
	RedisAddr          string
	RedisDB            int
	JWTSecret          string
	ServerPort         string
	OSSEndpoint        string
	OSSAccessKeyId     string
	OSSAccessKeySecret string
	OSSBucketName      string
}

// LoadConfig 函数用于加载配置信息
func LoadConfig() (*Config, error) {
	// 尝试加载 .env 文件
	err := godotenv.Load()
	if err != nil {
		log.Println("未找到 .env 文件，将使用环境变量")
	}

	// 从环境变量中读取配置信息
	dbHost := getEnv("DB_HOST", "localhost")
	dbPort := getEnv("DB_PORT", "3306")
	dbUser := getEnv("DB_USER", "root")
	dbPassword := getEnv("DB_PASSWORD", "password")
	dbName := getEnv("DB_NAME", "cloud_order")
	redisAddr := getEnv("REDIS_ADDR", "localhost:6379")
	redisDB := getEnvInt("REDIS_DB", 0)
	jwtSecret := getEnv("JWT_SECRET", "default_secret")
	serverPort := getEnv("SERVER_PORT", "8080")
	ossEndpoint := getEnv("OSS_ENDPOINT", "oss-cn-beijing.aliyuncs.com")
	ossAccessKeyId := getEnv("OSS_ACCESS_KEY_ID", "your_access_key_id")
	ossAccessKeySecret := getEnv("OSS_ACCESS_KEY_SECRET", "your_access_key_secret")
	ossBucketName := getEnv("OSS_BUCKET_NAME", "your_bucket_name")

	// 构建配置结构体
	config := &Config{
		DBHost:             dbHost,
		DBPort:             dbPort,
		DBUser:             dbUser,
		DBPassword:         dbPassword,
		DBName:             dbName,
		RedisAddr:          redisAddr,
		RedisDB:            redisDB,
		JWTSecret:          jwtSecret,
		ServerPort:         serverPort,
		OSSEndpoint:        ossEndpoint,
		OSSAccessKeyId:     ossAccessKeyId,
		OSSAccessKeySecret: ossAccessKeySecret,
		OSSBucketName:      ossBucketName,
	}

	return config, nil
}

// getEnv 获取环境变量的值，如果不存在则使用默认值
func getEnv(key, defaultValue string) string {
	value := os.Getenv(key)
	if value == "" {
		return defaultValue
	}
	return value
}

// getEnvInt 获取环境变量的整数值，如果不存在则使用默认值
func getEnvInt(key string, defaultValue int) int {
	valueStr := os.Getenv(key)
	if valueStr == "" {
		return defaultValue
	}
	var value int
	_, err := fmt.Sscanf(valueStr, "%d", &value)
	if err != nil {
		log.Printf("无法将环境变量 %s 转换为整数，使用默认值 %d", key, defaultValue)
		return defaultValue
	}
	return value
}
